﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Linq;

namespace DBLOG.KmlWrapper
{
    /// <summary>
    /// Parses KML stream into objects
    /// Can only capture coordinates - style is not applied
    /// </summary>
    public static class KmlParser
    {
        public static KmlDocument ParseKml(string kmlUrl)
        {
            XElement document = XElement.Load(kmlUrl);
            XNamespace ns = "http://earth.google.com/kml/2.0";
            XElement element = document.Descendants().Where(a => a.Name.LocalName == "coordinates").FirstOrDefault();          

            string[] coordinates = null;

            if (element != null)
                coordinates = element.Value.Split(',');

            KmlDocument kmlDocument = null;
            KmlPlacemark kmlPlacemark;
            KmlPoint kmlPoint;

            if (coordinates != null)
            {
                kmlDocument = new KmlDocument();
                kmlPlacemark = new KmlPlacemark();
                kmlPoint = new KmlPoint() { Longitude = coordinates[0], Latitude = coordinates[1] };
                kmlPlacemark.KmlPoint = kmlPoint;
                kmlDocument.Add(kmlPlacemark);
            }

            return kmlDocument;
        }
    }
}
